<template>
  <div class="container">
    <h3>新增学生</h3>
    姓名：
    <el-input size="small " type="text" v-model="student.name" /> <br />
    年龄；
    <el-input size="small " type="text" v-model="student.age" /><br />
    性别：
    <el-input size="small " type="text" v-model="student.gender" /><br />
    专业：<el-select v-model="student.subjectsId" placeholder="请选择">
      <el-option v-for="item in subjects" :key="item._id" :label="item.name"
        :value="item._id">
      </el-option>
    </el-select>
    <br />
    班级：<el-select v-model="student.classesId" placeholder="请选择">
      <el-option v-for="item in classes" :key="item._id" :label="item.name"
        :value="item._id">
      </el-option>
    </el-select>

    <div class="img">
      <input type="file" @change="upImg" />
    </div>
    <el-button type="primary" @click="add">新增学生</el-button>
  </div>
</template>

<script>
import { createNamespacedHelpers } from "vuex";
const { mapState, mapActions } = createNamespacedHelpers("subject");
const { mapState: imgState, mapActions: imgAction } = createNamespacedHelpers("upimg");
export default {
  data() {
    return {
      student: {


      },
      classes: "",
    };
  },
  computed: {
    ...mapState(['subjects']),
    ...imgState(['imgsrc'])
  },
  methods: {
    //获取专业
    ...mapActions(['getSubject']),
    // 图片上传
    ...imgAction(["upImg"]),
    // 增加
    add() {
      this.$api.studentApi.addStudent({ ...this.student, image: this.imgsrc }).then(({ data }) => {
        this.$message.success(data.message);
        console.log(data);
      });
    },
    // 通过id获取班级
    getClasses() {
      this.$api.classApi.getClassById(
        {
          params: {
            subjectsId: this.student.subjectsId,
          },
        })
        .then(({ data }) => {
          // console.log(data.data.rows);
          this.classes = data.data.rows;
        });
    },
  },
  created() {
    this.getSubject();
  },
  watch: {
    "student.subjectsId"(a, b) {
      if (b) this.student.classesId = null
      this.getClasses();
    },
  },
};
</script>

<style scoped>
.img {
  margin-bottom: 10px;
}
.container {
  background-color: #fff;

  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 30px;
  height: 550px;
}
</style>
